# controllers/workflow_controller.py
from flask import Blueprint, request, jsonify
from services.workflow_service import WorkflowService
from services.approval_service import ApprovalService
from utils.exceptions import WorkflowException
from models.workflow import WorkflowInstance

workflow_bp = Blueprint('workflow', __name__)

@workflow_bp.route('/workflows', methods=['POST'])
def create_workflow():
    data = request.json
    try:
        instance = WorkflowService.start_workflow(
            data['template_id'],
            data['form_data'],
            data['initiator_id']
        )
        return jsonify({
            "instance_id": instance.id,
            "current_step": instance.current_step
        }), 201
    except Exception as e:
        raise WorkflowException(str(e), code=400)

@workflow_bp.route('/workflows/<instance_id>/progress', methods=['GET'])
def get_progress(instance_id):
    """获取审批进度"""
    instance = WorkflowInstance.query.get_or_404(instance_id)
    progress = ApprovalService.get_approval_progress(instance_id)
    return jsonify({
        "status": instance.status,
        "current_step": instance.current_step,
        "progress": progress
    })

@workflow_bp.route('/templates/<int:template_id>/steps', methods=['POST'])
def create_step():
    """创建审批步骤"""
    data = request.json
    try:
        step = WorkflowStep(
            template_id=template_id,
            step_order=data['step_order'],
            approver_ids=data['approver_ids'],  # 直接接收用户ID列表
            cc_user_ids=data.get('cc_user_ids', []),
            step_type=data.get('step_type', 'SERIAL'),
            approve_mode=data.get('approve_mode', 'ANY')
        )
        db.session.add(step)
        db.session.commit()
        return jsonify({"step_id": step.id}), 201
    except Exception as e:
        raise WorkflowException(str(e), code=400)